package com.yfuxdeer.youchat.adapter;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.yfuxdeer.youchat.R;
import com.yfuxdeer.youchat.pojo.Message;
import com.yfuxdeer.youchat.pojo.User;
import com.yfuxdeer.youchat.utils.ImageUtil;
import com.yfuxdeer.youchat.utils.Store;

import java.util.List;

public class MessageInfoListAdapter extends BaseAdapter {

    private final static String TAG = MessageInfoListAdapter.class.getSimpleName();
    private List<Message> messageList;
    private Context context;
    private User currentUser;
    private Store store = Store.getInstance();

    public MessageInfoListAdapter(List<Message> messageItemList, Context context, User currentUser) {
        this.messageList = messageItemList;
        this.context = context;
        this.currentUser = currentUser;
    }

    @Override
    public int getCount() {
        if (messageList == null) return 0;
        return messageList.size();
    }

    @Override
    public Object getItem(int i) {
        return messageList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder = null;
        if (view == null) {
            view = View.inflate(context, R.layout.message_info, null);
            holder = new ViewHolder();
            holder.senderHead = view.findViewById(R.id.senderHead);
            holder.msg = view.findViewById(R.id.msg);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        Message message = messageList.get(i);
        if (message.getFrom().equals(store.getCurrentUser().getUsername())) {
            ImageUtil.glideLoad(context, message.getFrom(), store.cacheState, holder.senderHead);
        } else {
            ImageUtil.glideLoad(context, message.getFrom(), 0, holder.senderHead);
        }
        holder.msg.setText(message.getMsg());
        if (!(message.getFrom().equals(currentUser.getUsername()))) {
            holder.msg.setBackground(context.getDrawable(R.drawable.tv_radius_oppsite));
        } else {
            holder.msg.setBackground(context.getDrawable(R.drawable.tv_radius_me));
        }
        return view;
    }

    @Override
    public void notifyDataSetChanged() {
        Log.e(TAG, "我被更新了");
        super.notifyDataSetChanged();
    }

    public class ViewHolder {
        public ImageView senderHead;
        public TextView msg;
    }
}
